package com.gtfrank.web.servlet.day2;

import com.gtfrank.web.servlet.pojo.User;
import com.gtfrank.web.servlet.service.IUserService;
import com.gtfrank.web.servlet.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ProjectName: sudacoursetrainging
 * @ClassName: LoginServlet
 * @PackageName:com.gtfrank.web.servlet.day2
 * @Description:
 * @Author: frank
 * @Date: 2021/4/28 16:19
 * @Version v1.0
 */
@WebServlet(value = "/user/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        IUserService userService = new UserServiceImpl();
        /**
         * 登录成功显示用户登录成功，失败显示失败
         */
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        //获得用表单提交的用户名和密码
        // 参数的name 就是input框的name的值
        String name = req.getParameter("userName");
        String password = req.getParameter("password");
        try {
            User user = userService.login(name, password);
            if (user != null) {
                out.println("欢迎" + user.getName() + "登录成功");
            } else {
                out.println("登录失败");
            }
        }catch (Exception e){
            out.println("登录失败");
            e.printStackTrace();
        }
        out.flush();;
        out.close();
    }
}
